<template>
  <div class="mform-setting-function-list" v-loading="pending">
    <div class="mform-setting-function-list-block">
      <draggable
        animation="180"
        class="nested-draggable"
        tag="div"
        :list="lists"
        filter=".undraggable"
        @end="draggableEndHandler"
      >
        <div
          class="mform-setting-function-list-item"
          v-for="(item, index) in lists"
          :key="index"
          v-show="show(item)"
        >
          <div class="mform-setting-function-list-item-header">
            <span class="mform-setting-function-list-item-header-title">
              功能 {{ index + 1 }}
              <span v-if="item.isSystem">(系统功能)</span>
            </span>
            <span
              class="mform-setting-function-list-item-header-delete"
              @click="deleteItem(index)"
              v-if="!item.isSystem"
            >
              删除
            </span>
          </div>
          <div class="mform-setting-function-list-content-main">
            <mform-item :label="titleField.displayName">
              <form-text
                :value="item.specialName"
                :field="titleField"
                :class="{ noInput: item.isSystem }"
                @input="value => updateTitle(value, index)"
              />
              <!-- <div
                class="language-config"
                @click="openMultilinguaDialog(index)"
                v-if="isOpenMultiLanguage && !item.isSystem"
              >
                <i class="iconfont icon-earth"></i>
              </div> -->
              <div
                v-if="isOpenMultiLanguage && !item.isSystem"
              >
                <base-select-language
                    :selectKey="index" 
                    :field="titleField"
                    :defaultOption="{
                      formType:'text',
                    }"
                    defaultFormType="text"
                    :defaultValue="lists[index].specialName"
                    :defaultValueLanguage="lists[index].specialNameLanguage"
                    :isFill="false"
                    @save="updateFields"
                  >
                </base-select-language>
              </div>
            </mform-item>

            <template v-if="!item.isSystem">
              <mform-item :label="typeField.displayName">
                <form-select
                  :field="typeField"
                  :value="item.type"
                  :source="typeDataSource"
                  @input="value => updateType(value, index)"
                  placeholder="[必选]请选择关联"
                  :clearable="false"
                />
              </mform-item>
              <mform-item v-if="item.type == 'PAAS'" class="noStar">
                <form-select
                  :field="linkField"
                  :value="item.templateBizId"
                  :source="paasDataSource.value"
                  @input="value => updatePass(value, index)"
                  placeholder="[必选]请选择PAAS类型"
                  :clearable="false"
                />
              </mform-item>
              <mform-item v-if="item.type == 'customLink'" class="noStar">
                <form-text
                  :field="customLinkField"
                  :value="item.url"
                  :placeholder="customLinkField.placeholder"
                  @input="value => updateCustomLink(value, index)"
                />
              </mform-item>
            </template>
          </div>
          <div v-if="item.type === 'productList'" class="mform-setting-function-list-content-other">
            <div class="title">{{$t('common.form.preview.relateTask.tip1')}}</div>
            <el-select
              v-model="relateProductFields"
              :placeholder="$t('common.base.pleaseSelect')"
              multiple
              :multiple-limit="14"
              @change="updateProduct(index)"
            >
              <el-option
                v-for="(item, zindex) in productAllFields"
                :key="`${zindex}_${item.fieldName}`"
                :label="item.displayName"
                :value="item.fieldName"
                :disabled="item.disabled"
              >
              </el-option>
            </el-select>
          </div>
        </div>
      </draggable>
    </div>
    <el-button
      v-if="!isMax"
      icon="el-icon-plus"
      class="mform-setting-photo-article-list-item-add-button"
      plain
      type="primary"
      @click="add"
    >
      添加
    </el-button>
    <!-- 多语配置弹出框 -->
    <MultilingualDialog
      ref="multilingualDialogRef"
      title="多语配置"
      :language-list="languageList"
      @update="updateFields"
    />
  </div>
</template>

<script>
/* component */
import draggable from 'vuedraggable';
import MultilingualDialog from '@src/component/compomentV2/MultilingualDialog/index.vue';
/* model */
import {
  FormTitleSettingTitleNameField,
  FormTitleSettingLinkField,
  FormTitleSettingTypeField,
  FormTitleSettingCustomLinkField
} from 'src/mform/components/FormFunctionList/FormFunctionListModel.ts';
/* util */
import _ from 'lodash';
import { getRootWindow } from '@src/util/dom';
import { isNotUndefined } from '@src/util/type';
import { getUserId } from '@src/util/storage.ts'
/* mixin */
import { VersionControlPaasMixin, VersionControlLinkCMixin } from '@src/mixins/versionControlMixin';
/* api*/
import { getProductFieldsV2 } from '@src/api/ProductApi';
const productFieldsShow = ['name', 'catalogId' ,'serialNumber', 'qualityInfo'];
export default {
  name: 'mform-setting-function-list',
  mixins: [
    VersionControlPaasMixin, 
    VersionControlLinkCMixin
  ],
  props: {
    value: {
      type: Array,
      default: () => [],
    },
    titleName: {
      type: String,
      default: '标题',
    },
    isValidateTitle: {
      type: Boolean,
      default: false,
    },
    titleMaxlength: {
      type: Number,
      default: 10,
    },
    languageList: {
      type: Array,
      default: () => [],
    },
    isOpenMultiLanguage: {
      type: Boolean,
      default: false,
    },
    max: {
      type: Number,
      default: 10,
    },
    languageList: {
      type: Array,
      default: () => [],
    },
  },
  components: {
    draggable,
    MultilingualDialog,
  },
  inject: ['paasDataSource'],
  data() {
    return {
      multilingualIndex: 0,
      productAllFields: [], // 所有的产品字段
      relateProductFields: [], // 选择的产品字段
      pending: true,
    };
  },
  computed: {
    isOpenServiceMall() {
      const RootWindow = getRootWindow(window);
      return RootWindow?.grayAuth?.SERVICE_MALL ?? false;
    },
    titleField() {
      return FormTitleSettingTitleNameField;
    },
    linkField() {
      return FormTitleSettingLinkField;
    },
    typeField() {
      return FormTitleSettingTypeField;
    },
    customLinkField(){
      return FormTitleSettingCustomLinkField
    },
    lists() {
      
      let lists = this.value;
      
      if (!this.isOpenServiceMall) {
        let addressListItem = lists.find(v => v.type === 'addressList');
        let addressListIndex = lists.findIndex(v => v.type === 'addressList');
        if (addressListItem) {
          lists.splice(addressListIndex, 1);
          lists.push(addressListItem);
        }
      }
      
      const toolByVersionShowMap = {
        orderList: this._isShowLinkCOrderList,
        multilingual: this._isShowLinkCMultiLanguageList,
        addressList: this._isShowLinkCAddressList
      }
      
      return lists.filter(item => {
        
        const needVersionJudgeList = ['orderList', 'multilingual', 'addressList']
        if (needVersionJudgeList.includes(item.type)) {
          
          const isShow = toolByVersionShowMap[item.type]
          return isNotUndefined(isShow) ? isShow : false
          
        }
        
        return true
        
      })
    },
    isMax() {
      return this.value.length >= this.max;
    },
    show() {
      return function (item) {
        if (item.type == 'addressList' && !this.isOpenServiceMall) return false;

        let list = [
          'orderList',
          'productList',
          'collectionList',
          'addressList',
        ];
        if (this?.$i18n.locale != 'zh' && list.includes(item.type))
          return false;
        return true;
      };
    },
    shbPaas() {
      const rootWindow = getRootWindow(window);
      return rootWindow?.grayAuth?.shbPaas ?? false;
    },
    typeDataSource() {
      let typeDataSource = [
        {
          text: '自定义链接',
          value: 'customLink',
        }
      ];
      
      // 纯客服云版本不显示PAAS
      if (this.shbPaas && this._isShowPaasModule) {
        typeDataSource.push({
          text: 'PAAS',
          value: 'PAAS',
        });
      }
      
      return typeDataSource;
    },
    // 获取产品列表字段
    productField() {
      return this.lists?.find(item => item.type === 'productList')
    },
    userId() {
      return getUserId();
    },
  },
  methods: {
    setOrder() {
      let lists = _.cloneDeep(this.lists);
      lists.map((v, i) => {
        v.order = i;
      });
      this.update(lists);
    },
    draggableEndHandler() {
      this.$nextTick(() => {
        this.setOrder();
      });
    },
    update(value) {
      this.$emit('input', value);
    },
    updateTitle(value, index) {
      let lists = _.cloneDeep(this.lists);
      lists[index].specialName = value;
      this.$set(lists[index].specialNameLanguage, 'zh', value);
      this.update(lists);
    },
    updateType(value, index) {
      let item = this.typeDataSource.find(v => v.value == value);
      if (!item) return;
      let lists = _.cloneDeep(this.lists);
      lists[index].type = item.value;
      lists[index].url = "";
      this.update(lists);
    },
    updatePass(value, index) {
      let item = this.paasDataSource.value.find(v => v.templateBizId == value);
      if (!item) return;
      let lists = _.cloneDeep(this.lists);
      lists[index].templateBizId = item.templateBizId;
      lists[index].templateName = item.templateName;
      lists[index].url = item.url;
      this.update(lists);
    },
    updateCustomLink(value, index) {
      let lists = _.cloneDeep(this.lists)
      lists[index].url = value
      this.update(lists)
    },
    openMultilinguaDialog(index) {
      this.multilingualIndex = index;
      if (
        this.lists[index].specialNameLanguage?.['zh'] !==
        this.lists[index].specialName
      ) {
        const _value = _.cloneDeep(this.lists[index].specialNameLanguage);
        _value['zh'] = this.lists[index].specialName;
        this.$refs.multilingualDialogRef.openDialog(_value);
      } else {
        this.$refs.multilingualDialogRef.openDialog(
          this.lists[index].specialNameLanguage
        );
      }
    },
    updateFields(value, index) {
      this.multilingualIndex = index;
      let lists = _.cloneDeep(this.lists);
      lists[this.multilingualIndex].specialName = value['zh'];
      lists[this.multilingualIndex].specialNameLanguage = value;
      this.update(lists);
    },
    deleteItem(index) {
      let lists = _.cloneDeep(this.lists);
      lists.splice(index, 1);
      this.update(lists);
    },
    add() {
      let list = _.cloneDeep(this.lists);

      list.push({
        url: '',
        icon: 'icon-Partition',
        type: '',
        order: list.length + 1,
        isSystem: 0,
        grayState: true,
        specialName: '',
        templateName: '',
        templateBizId: '',
        specialNameLanguage: {
          zh: '',
          en: '',
          ja: '',
          ko: '',
        },
      });
      this.update(list);
    },
    updateProduct(index) {
      let lists = _.cloneDeep(this.lists);
      this.$set(lists[index], 'setting', this.relateProductFields);
      this.update(lists);
    },
    //处理产品字段
    async handlerProductFields() {
      try {
        this.pending = true;

        await this.getAllProductFields()

        // 过滤产品中被删除的字段，避免匹配不上
        const relateProductFields = this.productField?.setting ?? []

        this.relateProductFields = relateProductFields
            ?.filter(item => this.productAllFields?.findIndex((zitem) => item === zitem.fieldName) > -1) ?? [];

        if(!this.relateProductFields?.length) this.relateProductFields = productFieldsShow;

      } catch (e) {
        console.error(e)
      } finally {
        this.pending = false;
      }
    },

    // 查询所有的产品字段
    async getAllProductFields() {
      try {
        const { data } = await getProductFieldsV2({isFromSetting: false});

        // 过滤电子签名，分割线，说明信息，附件，富文本，服务商，连接器，物流信息
        this.productAllFields = data
            ?.filter(item => !['autograph', 'separator', 'info', 'attachment', 'richtext', 'serviceProviders', 'connector', 'logistics'].includes(item.formType))
            ?.map(item => {
              return {
                fieldName: item.fieldName,
                formType: item.formType,
                displayName: item.displayName,
                disabled: productFieldsShow.includes(item.fieldName)
              }
            }) ?? []

      } catch (e) {
        console.error(e)
      }
    },
  },
  mounted() {
    this.handlerProductFields();
  }
};
</script>

<style lang="scss" scoped>
.mform-setting-function-list {
  padding-bottom: 30px;
}
.mform-setting-function-list-header {
  padding: 0 16px;
  line-height: 22px;
  &-title {
    color: #595959;
  }
  &-subtitle {
    color: #8c8c8c;
    display: inline-block;
    font-size: 12px;
    margin-left: 12px;
  }
}

.mform-setting-function-list-item {
  background-color: #fafafa;
  &-header {
    display: flex;
    justify-content: space-between;
    line-height: 22px;
    &-title {
      color: #bfbfbf;
    }
    &-delete {
      cursor: pointer;
      color: #8c8c8c;
      &:hover {
        color: $color-danger;
      }
    }
  }
}

.mform-setting-function-list-item-header {
  margin-bottom: 4px;
}

.mform-setting-function-list-item-content {
  display: flex;
  margin-top: 8px;
  .el-upload,
  .replace-image {
    background-color: #fbfdff;
    border: 1px dashed #c0ccda;
    border-radius: 3px;
    display: flex;
    height: 50px;
    width: 50px;
    line-height: 50px;
    cursor: pointer;

    img {
      width: 48px;
      height: 48px;
      position: relative;
      top: -2px;
    }
    i {
      width: 48px;
      line-height: 48px;
      font-size: 24px;
    }
  }
}

.mform-setting-function-list-block {
  background-color: #fafafa;
  margin-top: 15px;
}

.mform-setting-function-list-content-image {
  width: 40px;
  margin-right: 14px;
  .el-upload-list {
    display: none;
  }
}

.mform-setting-function-list-content-main {
  flex: 1;
  .form-item {
    padding: 0 0 0 16px !important;
  }
}

.mform-setting-function-list-content-other {
  padding: 8px 0 8px 16px;
  display: flex;
  .title {
    width: 60px !important;
    flex-shrink: 0;
    align-content: center;
  }
  .el-select {
    width: 100%;

    ::v-deep .el-select__tags {
      .el-tag__close {
        display: none !important;
      }
    }
  }
}

.mform-setting-function-list-item-add-button {
  margin-top: 24px;
  margin-left: 16px;
  margin-right: 16px;
  margin-bottom: 32px;
  width: calc(100% - 32px);
  height: 40px;
}

.sortable-ghost {
  background-color: #fff;
}

.mform-setting-function-list-item {
  cursor: move;
  padding: 15px 16px 0;
  &:hover {
    background-color: #fff;
  }
  ::v-deep .form-item {
    label {
      width: 60px !important;
    }
  }
}

.mform-setting-function-list-header-title {
  color: #595959;
}

.custom-link-item {
  .form-item-label-text {
    display: none;
  }
}

.language-config {
  width: 32px;
  height: 28px;
  text-align: center;
  line-height: 28px;
  background: #f5f8fa;
  border-radius: 4px;
  border: 1px solid #cbd6e2;
  cursor: pointer;
  margin-left: 5px;
}

.event-link {
  font-size: 13px;
  color: #595959;
  margin: 0 0 10px 70px;

  span {
    color: $color-primary-light-6;
    cursor: pointer;
  }
}
</style>
<style lang="scss">
.mform-setting-function-list {
  .form-item-control-content {
    display: flex;
    align-items: center;
  }
  .form-item-control {
    width: auto;
    max-width: 100%;
  }
}
.noInput {
  pointer-events: none;
  input {
    -webkit-text-fill-color: #bfbfbf;
    border-color: #d9d9d9;
    background-color: #f5f5f5 !important;
  }
}
.noStar {
  .form-item-required {
    display: none !important;
  }
}
</style>
